import React, {Component} from 'react';
import NavigationBar from '../../Common/NavigationBar/NavigationBar.jsx'
//import Using ES6 syntax
import WeUI from 'react-weui';

//import styles
import 'weui';
import 'react-weui/build/dist/react-weui.css';
import {CSS} from '../styles/UserCenterStyle.css';
import $ from 'jquery';
const {
    Toptips,
    Picker,
} = WeUI;

//算高
let screenWidth = $(window).width();
let screenHeight = $(window).innerHeight();
let baseFontSize = 10 * screenWidth / 375;
let changeStyle = {
    display: "inline-block",
    fontSize: "1rem",
    width: "7rem",
    // marginTop: "0.3rem",
    verticalAlign: "middle"
};
let changeImg = {
    width: "1.5rem",
    height: "1.5rem",
    verticalAlign: "text-bottom",
};

let editImg = {
    width: "2rem",
    height: "2rem",
    verticalAlign: "middle",
    marginRight: "1rem"
};

let teamNameStyle = {
    textAlign: "center",
    maxWidth: "22rem",
    // marginLeft: "7.2rem",
    display: "inline-block",
    fontSize: "1.4rem"
};
let cellImg = {
    display: "block",
    width: "20px",
    marginRight: "10px",
    marginLeft: "10px"
};

export default class UserCenter extends Component {
    constructor(props) {
        super(props);
        this.LeftClick = this.LeftClick.bind(this);
        this.realName = this.realName.bind(this);
        this.SetName = this.SetName.bind(this);
        this.TeamInfo = this.TeamInfo.bind(this);
        this.MeetingRoomInfo = this.MeetingRoomInfo.bind(this);
        this.TeamInfo = this.TeamInfo.bind(this);
        this.UserInfo = this.UserInfo.bind(this);
        this.reserveMeetingRoom = this.reserveMeetingRoom.bind(this);
        this.state = {
            type: 2,
            userName: "",
            hasName: false,
            hasTeam: false,
            teamId: 0,
            teamData: [],
            showWarn: false,
            warnTimer: null,
            isCompanyAdmin:null,
            tipText: "",
            picker_index: 0,
            picker_show: false,
            picker_value: '',
            picker_group: [
                {
                    items: [
                    ]
                }
            ],
        };
        this.state.warnTimer && clearTimeout(this.state.warnTimer);
    }

    showWarn(text) {
        this.setState({showWarn: true, tipText: text});

        this.state.warnTimer = setTimeout(() => {
            this.setState({showWarn: false});
        }, 2000);
    }

    hide() {
        this.setState({
            picker_show: false,
        })
    }

    componentWillMount() { //组件即将被插入
        this.getIsCompanyAdmin();
        //获取个人信息(名字)'
        let userName = "";
        let hasName = false;
        fetch(getHost() + "/user/detail", {
            credentials: 'include',
        }).then(response => response.json())
            .then(d => {
                if (d.success) {
                    if (d.data.nickyName){
                        userName = d.data.nickyName;
                        hasName = true;
                    } else {
                        userName = "点击设置姓名";
                    }
                    let self = this;
                    fetch(getHost() + "/team", {
                        credentials: 'include'
                    }).then(response => response.json())
                        .then(data => {
                            if (data.success) {
                                if (data.data && data.data.length > 0) {
                                    let groupData = [];
                                    let pickItem = {};
                                    let idStore = data.data[0].id;
                                    let chooseTeam = data.data[0].name;
                                    if (chooseTeam.length > 15) {
                                        chooseTeam = chooseTeam.substring(0, 15) + "...";
                                    }
                                    let localId=localStorage.getItem("teamId")
                                    if (localId) {
                                        for (let i = 0; i < data.data.length; i++) {
                                            if (data.data[i].id === parseInt(localId)) {
                                                idStore = localId;
                                                break;
                                            }
                                        }
                                    }
                                    //构建筛选框数据
                                    let index = 0;
                                    for (let i = 0; i < data.data.length; i++) {

                                        let teamItem = data.data[i];
                                        if (teamItem.name.length > 15) {
                                            teamItem.name = teamItem.name.substring(0, 15) + "...";

                                        }
                                        if (idStore && parseInt(idStore) === teamItem.id) {
                                            console.log("get idStore :" + idStore);
                                            chooseTeam = teamItem.name;
                                            index = i;
                                            console.log("set team id select id: " + index);
                                        }
                                        pickItem = {
                                            id: teamItem.id,
                                            label: teamItem.name
                                        };
                                        groupData.push(pickItem);
                                    }

                                    console.log(groupData);
                                    self.setState({
                                        userName: userName,
                                        hasName: hasName,
                                        hasTeam: true,
                                        teamId: idStore,
                                        picker_index: index,
                                        picker_value: chooseTeam,
                                        picker_group: [{items: groupData}],
                                        showToptips: false
                                    });
                                }
                            } else {
                                self.showWarn();
                            }
                        }).catch(e => {
                        self.showWarn();
                    });
                    // this.setState({userName: userName});
                } else {
                    this.showWarn("网络出现了点问题");
                }
            });
    }


    //获取是否是公司管理员
    getIsCompanyAdmin(){
        let self = this;
        fetch(getHost() + "/user/isTeamAdmin", {
            method: 'get',
            credentials: 'include'
        }).then(response => response.json())
            .then(d => {
                if (d.success) {
                    self.setState({
                        isCompanyAdmin:d.data,
                    })
                } else{
                    self.showWarn(d.error.message);
                }
            });
    }
    LeftClick() {
        if (wx){
            wx.closeWindow();
        }
    }


    //认证
    realName() {
        this.showWarn("认证功能完善中")
    }

    //设置名字
    SetName() {
        location.hash = "/SetName?from=UserCenter";
    }

    //创建团队
    CreateTeam() {
        location.hash = "/CreateTeam";
    }

    //预定会议室
    reserveMeetingRoom(){
        if(this.state.hasTeam){ //存在公司
            location.hash = "/MeetingRoom";
        }else{//没有公司
            location.hash = "/CreateTeam";
        }
    }
    MeetingRoomInfo() {
        // 会议室订单
        location.hash = "/MeetingRoomHistory?teamId=" + this.state.teamId + "&isCompanyAdmin=" + this.state.isCompanyAdmin + "&teamName=" +this.state.picker_value;
    }

    TeamInfo() {
        // 团队信息
        location.hash = "/TeamInfoEdit?teamId=" + this.state.teamId;
    }

    UserInfo() {
        // 个人信息
        location.hash = "/UserInfo";
    }

    render() {

        this.state.type = 2;
        this.state.hasTeam = true;
        if (this.state.type == 1) {//无认证
            return (
                <div>
                    <NavigationBar Title="个人中心" LeftBar="true" LeftTitle="返回"
                                   LeftIconSrc="/iot-meeting/assets/images/common/nav_back_icon.png" LeftClick={this.LeftClick}/>
                    <div className="UserIconDiv">
                        <img className="NoUserPic" src="/iot-meeting/assets/images/user/NoUserPic.png"/>
                        <div className="TipTitleDiv" onClick={this.realName}>点击实名认证</div>
                    </div>
                    <Toptips type="warn" show={this.state.showWarn}>{this.state.tipText}</Toptips>
                </div>
            )
        } else if (this.state.type == 2) {//有认证
            let remainHeight = screenHeight - (15.4) * baseFontSize  + "px";
            let nameImgDiv = null;
            let hasTeamDiv = null;
            if (this.state.hasName) {
                nameImgDiv = <div></div>
            } else {
                nameImgDiv = <img
                    src="/iot-meeting/assets/images/user/user_name_edit.png"
                    style={editImg}/>;
            }
            if (this.state.hasTeam) {
                hasTeamDiv = <div className="teamSelectDiv">
                    <div style={teamNameStyle}>
                        {this.state.picker_value}</div>
                    <div style={changeStyle} onClick={e => {
                        e.preventDefault();
                        this.setState({picker_show: true})
                    }}><img
                        src="/iot-meeting/assets/images/user/btn_change_team.png"
                        style={changeImg}/>切换企业
                    </div>
                    <Picker
                        onChange={selected => {
                            let value = '';
                            let teamId = "";
                            selected.forEach((s, i) => {
                                value = this.state.picker_group[i]['items'][s].label;
                                teamId = this.state.picker_group[i]['items'][s].id;
                                localStorage.setItem("teamId", teamId);
                            });
                            this.setState({
                                teamId: teamId,
                                picker_value: value,
                                picker_show: false
                            });
                            fetch(getHost() + "/team/choose/" + teamId, {
                                method: 'POST',
                                credentials: 'include'
                            }).then(response => response.json())
                                .then(d => {
                                    if (d.success) {
                                        this.getIsCompanyAdmin();
                                    } else {
                                        this.showWarn(d.error.message);
                                    }
                                });
                        }}
                        defaultSelect={[this.state.picker_index]}
                        groups={this.state.picker_group}
                        show={this.state.picker_show}
                        onCancel={e => this.setState({picker_show: false})}
                        lang={{rightBtn: '完成'}}
                    />
                </div>;
            } else {
                hasTeamDiv = <div style={{fontSize: "1.4rem"}} onClick={this.CreateTeam}><img
                    src="/iot-meeting/assets/images/user/btn_add_team.png"
                    style={changeImg}/><span style={{marginLeft: "1rem"}}>创建企业</span>
                </div>;
            }


            let userName_box = "";
            let itemBox = "";
            // //是否是公司管理员
            // if(this.state.isCompanyAdmin){
            //     userName_box =  <div className="UserNameDiv" onClick={this.SetName}>{nameImgDiv}{this.state.userName}<span className="user_admin">管理员</span></div>
            //     itemBox = <div className="user_item_Box">
            //         <div className="item_content" onClick={this.MeetingRoomInfo}>
            //             <div className="meeting_item_icon"/>
            //             <div className="item_title">预定会议室</div>
            //         </div>
            //         <div className="item_content" onClick={this.MeetingRoomInfo}>
            //             <div className="contract_item_icon"/>
            //             <div className="item_title">会议室合约</div>
            //         </div>
            //         <div className="item_content"  onClick={this.UserInfo}>
            //             <div className="user_item_icon"/>
            //             <div className="item_title">个人信息</div>
            //         </div>
            //     </div>;
            // }else{
            //     userName_box =  <div className="UserNameDiv" onClick={this.SetName}>{nameImgDiv}{this.state.userName}</div>
            //     itemBox = <div className="user_item_Box">
            //         <div className="item_content" onClick={this.MeetingRoomInfo}>
            //             <div className="contract_item_icon"/>
            //             <div className="item_title">会议室合约</div>
            //         </div>
            //         <div className="item_content"  onClick={this.UserInfo}>
            //             <div className="user_item_icon"/>
            //             <div className="item_title">个人信息</div>
            //         </div>
            //     </div>;
            // }


            userName_box =  <div className="UserNameDiv" onClick={this.SetName}>{nameImgDiv}{this.state.userName}</div>
            itemBox = <div className="user_item_Box">
                <div className="item_content" onClick={this.reserveMeetingRoom}>
                     <div className="meeting_item_icon"/>
                    <div className="item_title">预定会议室</div>
                </div>
                <div className="item_content" onClick={this.MeetingRoomInfo}>
                    <div className="contract_item_icon"/>
                    <div className="item_title">会议室合约</div>
                </div>
                <div className="item_content"  onClick={this.UserInfo}>
                    <div className="user_item_icon"/>
                    <div className="item_title">个人信息</div>
                </div>
                <div className="item_content" style={{marginTop:"3rem"}} onClick={this.TeamInfo}>
                    <div className="team_item_icon"/>
                    <div className="item_title">企业信息</div>
                </div>
            </div>;
            return (
                <div style={{overflow:"hidden"}}>
                    <NavigationBar Title="个人中心" LeftBar="true" LeftTitle="返回"
                                   LeftIconSrc="/iot-meeting/assets/images/common/nav_back_icon.png" LeftClick={this.LeftClick}/>
                    <div className="UserIconDiv">
                        {userName_box}
                        {hasTeamDiv}
                    </div>
                    <div className="menu_layout" style={{height:remainHeight}}>
                        {itemBox}
                        <div className="bottom_layout">——智慧办公——</div>
                    </div>
                    <Toptips type="warn" show={this.state.showWarn}>{this.state.tipText}</Toptips>
                </div>
            )
        }
    }
}